package com.agileai.miscdp.hotweb.ui.editors.query;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;

import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.query.QueryFuncModel;
import com.agileai.miscdp.hotweb.ui.celleditors.CompositeProviderEditor;
import com.agileai.miscdp.hotweb.ui.celleditors.TableViewerKeyboardSupporter;
import com.agileai.miscdp.hotweb.ui.editors.AddOrDelOperation;
import com.agileai.miscdp.hotweb.ui.editors.BaseModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.Modifier;
import com.agileai.miscdp.hotweb.ui.editors.UpOrDownOperation;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.domain.KeyNamePair;
import com.agileai.util.StringUtil;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
/**
 * 明细Jsp配置页面
 */
public class QMDetailJspCfgPage extends Composite implements Modifier{
	private Text recordIdsText;
	private TableViewer tableViewer;
	private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());
	private Table table;
	private Text detailTitleText;
	private QueryFuncModel suFuncModel= null;
	private BaseModelEditor modelEditor = null;
	/**
	 * Create the composite
	 * @param parent
	 * @param style
	 */
	public QMDetailJspCfgPage(Composite parent,BaseModelEditor suModelEditor, int style) {
		super(parent, style);
		toolkit.adapt(this);
		toolkit.paintBordersFor(this);
		this.modelEditor = suModelEditor;
//		createContent();
	}
	public void createContent(){
		final GridLayout gridLayout = new GridLayout();
		gridLayout.verticalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.horizontalSpacing = 2;
		gridLayout.numColumns = 3;
		setLayout(gridLayout);

		final Label pageTitleLabel_2 = new Label(this, SWT.NONE);
		pageTitleLabel_2.setText("页面标题");

		detailTitleText = new Text(this, SWT.BORDER);
		detailTitleText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		new Label(this, SWT.NONE);

		final Label pageTitleLabel = new Label(this, SWT.NONE);
		pageTitleLabel.setText("记录标识");

		recordIdsText = new Text(this, SWT.READ_ONLY | SWT.BORDER);
		recordIdsText.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				fillRecordId();
			}
		});
		toolkit.adapt(recordIdsText, true, true);
		recordIdsText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

		final Button addrowButton_1 = new Button(this, SWT.NONE);
		addrowButton_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				fillRecordId();
			}
		});
		addrowButton_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		toolkit.adapt(addrowButton_1, true, true);
		addrowButton_1.setText("选择");

		final Label pageTitleLabel_1 = new Label(this,SWT.NONE);
		pageTitleLabel_1.setText("表单元素");

		tableViewer = new TableViewer(this,SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL
				| SWT.H_SCROLL);
		table = tableViewer.getTable();
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_table.widthHint = 523;
		table.setLayoutData(gd_table);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		final TableColumn labelColumn = new TableColumn(table, SWT.NONE);
		labelColumn.setWidth(120);
		labelColumn.setText("Label");

		final TableColumn codeColumn = new TableColumn(table, SWT.NONE);
		codeColumn.setWidth(120);
		codeColumn.setText("Code");
		
		final TableColumn tagTypeColumn = new TableColumn(table, SWT.NONE);
		tagTypeColumn.setWidth(70);
		tagTypeColumn.setText("TagType");
		
		final TableColumn dataTypeColumn = new TableColumn(table, SWT.NONE);
		dataTypeColumn.setWidth(70);
		dataTypeColumn.setText("DataType");

		final TableColumn formatColumn = new TableColumn(table, SWT.NONE);
		formatColumn.setWidth(120);
		formatColumn.setText("Format");
		tableViewer.setLabelProvider(new FormFieldLabelProvider());
		tableViewer.setContentProvider(new ArrayContentProvider());
		final CellEditor[] pageParamEditors = new CellEditor[table.getColumnCount()]; 
		pageParamEditors[0] = new TextCellEditor(table,0);
		pageParamEditors[1] = new CompositeProviderEditor(modelEditor,tableViewer,table);
		pageParamEditors[2] = new ComboBoxCellEditor(table,PageFormField.simpleTagTypes, SWT.READ_ONLY); 
		pageParamEditors[3] = new ComboBoxCellEditor(table,PageFormField.dataTypes, SWT.READ_ONLY);
		pageParamEditors[4] = new ComboBoxCellEditor(table,PageFormField.formats, SWT.READ_ONLY);
		
		tableViewer.setCellEditors(pageParamEditors);
		tableViewer.setColumnProperties(new String[]{"Label","Code","TagType","DataType","Format"}); 
		
		TableViewerKeyboardSupporter tableViewerSupporter = new TableViewerKeyboardSupporter(tableViewer); 
		tableViewerSupporter.startSupport();
		tableViewer.setCellModifier(new ICellModifier(){
			public boolean canModify(Object element, String property) {
				return true;
			}
			public Object getValue(Object element, String property) {
				PageFormField pageParameter = (PageFormField) element; 
				if (PageFormField.LABEL.equals(property)){
					return pageParameter.getLabel();
				}
				else if (PageFormField.CODE.equals(property)){
					return pageParameter.getCode();
				}
				else if (PageFormField.TAGTYPE.equals(property)){
					return getTagTypeIndex(pageParameter.getTagType());
				}
				else if (PageFormField.DATATYPE.equals(property)){
					return getDataTypeIndex(pageParameter.getDataType());
				}
				else if (PageFormField.FORMAT.equals(property)){
					return getFormatIndex(pageParameter.getFormat());
				}
				return null;
			}
			private int getTagTypeIndex(String tagType){
				int result = 0;
				for (int i=0;i < PageFormField.simpleTagTypes.length;i++){
					if (PageFormField.simpleTagTypes[i].equals(tagType)){
						result = i;
						break;
					}
				}
				return result;
			}
			private int getFormatIndex(String tagType){
				int result = 0;
				for (int i=0;i < PageFormField.formats.length;i++){
					if (PageFormField.formats[i].equals(tagType)){
						result = i;
						break;
					}
				}
				return result;
			}
			private int getDataTypeIndex(String dataType){
				int result = 0;
				for (int i=0;i < PageFormField.dataTypes.length;i++){
					if (PageFormField.dataTypes[i].equals(dataType)){
						result = i;
						break;
					}
				}
				return result;
			}
			public void modify(Object element, String property, Object value) {
				TableItem item = (TableItem)element;
				PageFormField pageParameter = (PageFormField) item.getData();
				boolean changed = false;
				if (PageFormField.LABEL.equals(property)){
					if (!String.valueOf(value).equals(pageParameter.getLabel())){
						pageParameter.setLabel(String.valueOf(value));
						changed = true;
					}
				}
				else if (PageFormField.TAGTYPE.equals(property)){
					Integer index = (Integer)value;
					if (index != -1 && !PageFormField.simpleTagTypes[index].equals(pageParameter.getTagType())){
						pageParameter.setTagType(PageFormField.simpleTagTypes[index]);
						changed = true;
					}
				}
				else if (PageFormField.DATATYPE.equals(property)){
					Integer index = (Integer)value;
					if (index != -1 && !PageFormField.dataTypes[index].equals(pageParameter.getDataType())){
						pageParameter.setDataType(PageFormField.dataTypes[index]);
						changed = true;
					}
				}
				else if (PageFormField.FORMAT.equals(property)){
					Integer index = (Integer)value;
					if (index != -1 && !PageFormField.formats[index].equals(pageParameter.getFormat())){
						pageParameter.setFormat(PageFormField.formats[index]);
						changed = true;
					}
				}
				if (changed){
					modelEditor.setModified(true);
					modelEditor.fireDirty();
					tableViewer.refresh();					
				}
			}
		});
		tableViewer.setInput(this.suFuncModel.getPageFormFields());
		
		final Composite composite = new Composite(this, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.verticalSpacing = 0;
		gridLayout_1.marginWidth = 0;
		gridLayout_1.marginHeight = 0;
		gridLayout_1.horizontalSpacing = 0;
		composite.setLayout(gridLayout_1);

		final Button addrowButton = new Button(composite, SWT.NONE);
		addrowButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				new AddOrDelOperation().addRow(tableViewer,PageFormField.class);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		addrowButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		addrowButton.setText("填充");

		final Button deleteButton = new Button(composite, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				new AddOrDelOperation().delRow(tableViewer);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		deleteButton.setText("删除");

		final Button upButton = new Button(composite, SWT.NONE);
		upButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int selectedIndex = tableViewer.getTable().getSelectionIndex();
				new UpOrDownOperation().moveUp(tableViewer, selectedIndex);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		upButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		upButton.setText("上移");

		final Button downButton = new Button(composite, SWT.NONE);
		downButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int selectedIndex = tableViewer.getTable().getSelectionIndex();
				new UpOrDownOperation().moveDown(tableViewer, selectedIndex);
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		downButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		downButton.setText("下移");

		final Button syncButton = new Button(composite, SWT.NONE);
		syncButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				List<ListTabColumn> listTabColumns = suFuncModel.getListTableColumns();
				List<PageFormField> pageFormFields = suFuncModel.getPageFormFields();
				MiscdpUtil.syncListLabel2FormField(listTabColumns,pageFormFields);
				tableViewer.refresh();
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		syncButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		toolkit.adapt(syncButton, true, true);
		syncButton.setText("同步");
	}
	public void dispose() {
		super.dispose();
	}
	protected void checkSubclass() {
	}

	public void setFuncModel(QueryFuncModel standardFuncModel) {
		this.suFuncModel = standardFuncModel;
	}

	public QueryFuncModel buildConfig() {
		suFuncModel.setDetailTitle(detailTitleText.getText());
		String rsIdColumnTemp = recordIdsText.getText();
		if (!StringUtil.isNullOrEmpty(rsIdColumnTemp)){
			suFuncModel.getRsIdColumns().clear();
			String[] rsIdColumnArray = rsIdColumnTemp.split(",");
			for (int i=0;i < rsIdColumnArray.length;i++){
				suFuncModel.getRsIdColumns().add(rsIdColumnArray[i]);
			}			
		}
		return this.suFuncModel;
	}
	public void initValues() {
		this.detailTitleText.setText(suFuncModel.getDetailTitle());
		String rsIdColumnTemp = ",";
		List<String> rsIds = suFuncModel.getRsIdColumns();
		if (rsIds.size() > 0){
			for (int i=0;i < rsIds.size();i++){
				rsIdColumnTemp = rsIdColumnTemp + rsIds.get(i);
				if (i < rsIds.size()-1){
					rsIdColumnTemp = rsIdColumnTemp + ",";
				}
			}
		}
		rsIdColumnTemp = rsIdColumnTemp.substring(1,rsIdColumnTemp.length());
		this.recordIdsText.setText(rsIdColumnTemp);
	}
	public TableViewer getTableViewer() {
		return tableViewer;
	}
	public void registryModifier() {
		detailTitleText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
		recordIdsText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				modelEditor.setModified(true);
				modelEditor.fireDirty();
			}
		});
	}
	public Text getRecordIdsText() {
		return recordIdsText;
	}
	
	public void fillRecordId(){
		QueryModelEditor queryModelEditor = (QueryModelEditor)modelEditor;
		Shell shell = queryModelEditor.getSite().getShell();
		QMBasicConfigPage qBasicConfigPage = queryModelEditor.getBasicConfigPage();
		String listSql = qBasicConfigPage.getListSqlText().getText();
		if (StringUtils.isBlank(listSql)){
			DialogUtil.showMessage(shell,"消息提示", "请先填写列表SQL！",DialogUtil.MESSAGE_TYPE.INFO);
			return;
		}
		
		RecordIdsDialog recordIdsDialog = new RecordIdsDialog(shell);

		SqlBuilder sqlBuilder = new SqlBuilder();
		String[] fields = sqlBuilder.parseFields(listSql);
		List<KeyNamePair> fieldsKeyNamePair = MiscdpUtil.buildKeyNamePairList(fields);
		recordIdsDialog.setInputKeyNamePairList(fieldsKeyNamePair);
		
		String recordIds = recordIdsText.getText();
		if (!StringUtils.isBlank(recordIds)){
			String[] keys = recordIds.split(",");
			List<KeyNamePair> selectedKeyNameparis = MiscdpUtil.buildKeyNamePairList(keys);
			for (int i=0;i < fieldsKeyNamePair.size();i++){
				KeyNamePair inputKeyNamePair = fieldsKeyNamePair.get(i);
				for (int j=0;j < selectedKeyNameparis.size();j++){
					KeyNamePair selectedKeyNamePair = selectedKeyNameparis.get(j);
					if (inputKeyNamePair.getKey().equals(selectedKeyNamePair.getKey())){
						recordIdsDialog.addSelectedKeyNamePair(inputKeyNamePair);					
					}
				}
			}
		}
		recordIdsDialog.open();
		if (recordIdsDialog.getReturnCode() == Dialog.OK){
			List<KeyNamePair> selectedKeyNamePair = recordIdsDialog.getSelectedKeyNamePairs();
			String[] selectKeys = MiscdpUtil.buildKeyArray(selectedKeyNamePair);
			String newIdText = StringUtils.join(selectKeys,",");
			recordIdsText.setText(newIdText);			
		}
	}
}
class FormFieldLabelProvider extends LabelProvider implements ITableLabelProvider {
	public String getColumnText(Object element, int columnIndex) {
		if (element instanceof PageFormField) {
			PageFormField p = (PageFormField) element;
			if (columnIndex == 0) {
				return p.getLabel();
			} else if (columnIndex == 1) {
				return p.getCode();
			} else if (columnIndex == 2) {
				return p.getTagType();
			} else if (columnIndex == 3) {
				return p.getDataType();			
			} else if (columnIndex == 4) {
				return p.getFormat();				
			}
		}
		return null;
	}
	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}
}
